import qs from 'qs';
import {Toast} from 'react-vant';

interface IResponse<T> {
    code: number;
    data: T | null;
    msg: string;
}

interface FetchRequest {
    (url: string, options: any): Promise<IResponse<any>>;
}

// export const baseUrl = 'http://120.48.24.52:3000';
// export const baseUrl = 'http://192.168.10.185:7788/cpapi';
export const baseUrl = '/cpapi';
// export const baseUrl = 'http://s9tditz.nat.ipyingshe.com/cpapi';


const request: FetchRequest = async (url, options) => {
    const {method = 'GET', data} = options;

    let getUrl = `${url}?${qs.stringify(options.data)}`;

    let isGet = method.toUpperCase() === 'GET';

    let myUrl = isGet ? getUrl : url;

    let myHeaders = {
        'Content-Type': 'application/json',
        "authorization": `Bearer ${sessionStorage.getItem('token')}`,
        ...options.headers
    }

    let myOptions = {
        method: method,
        headers: myHeaders,
        ...options.options
    }

    if (method.toUpperCase() == 'POST') {
        myOptions.body = JSON.stringify(data);
    }

    const response = await fetch(baseUrl + myUrl, myOptions);

    const res = await response.json();
    if (!response.ok) {
        throw new Error(res.message || 'Request failed');
    }
    if (res.code !== 1) {
        Toast({message: res.msg || '请求失败', position: 'top'});
        return Promise.reject(res);
        // throw new Error(res.message || '请求失败');
    }

    return res;

}

export default request;